<?php
namespace Service\DownloadMusic;
use Curl\Curl;
use Curl\MultiCurl;
use Service\DownloadMusic\DownWeb\CtFile;
use Sunra\PhpSimple\HtmlDomParser;
use Service\LoadingService;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/13
 * Time: 14:16
 */

class IndexService
{
	public $fileUrl = './Data/music.json';
	public $InterUrl = 'http://blog.sina.cn/dpool/blog/newblog/riaapi/mblog/get_articlelist.php';
	
	public $curlModel;
	public $lastDown = 0;
	
	public $Bar = false;

	public function __construct()
	{
		$this->curlModel = new MultiCurl();
	}
	
	public function getMusicFile(){
		$data = json_decode(file_get_contents($this->fileUrl),1);
		$file = [];
		foreach ($data as $key =>$value){
			$file[$key]['article_id']=$value['article_id'];
			$file[$key]['article_title']=$value['article_title'];
		}
		return $file;
	}
	
	public function updateMusicFile(){
		$total = 0;
		fwrite( STDOUT, sprintf( '%s: ', '正在更新' ) );
		$this->curlModel->success(function($obj) use (&$total){
			$data =  json_decode($obj->response,1);
			file_put_contents($this->fileUrl, json_encode($data['data']['msg'],1));
			$total =  $data['data']['total'];
		});
		$this->curlModel->error(function($obj){
			echo '请求失败';
		});
		$this->curlModel->addPost($this->InterUrl,['uid'=>6055728941,'pagesize'=>10000,'page'=>1,'class_id'=>'-1']);
		$this->curlModel->start();
		return $total;
	}
	
	public function DownMusicFile($id ){
		$getFileInfo = $this->getFileInfo($id);
		try{
			$dom  = HtmlDomParser::file_get_html($getFileInfo['url']);
			$href = '';
			foreach($dom->find('a') as $element){
				if(strpos($element->href,'ctfile')!==false){
					$href =  $element->href;
					break;
				}
			}

			if($href==''){
				\cli\err('解析下载地址失败');
			}else{
				$CtFile = new CtFile($href);
				$this->down($CtFile->getDownUrl(),$CtFile->getFileName());
			}
		}catch (\exception $e){
			\cli\err('解析下载地址失败');
		}

	}
	

	
	public function getFileInfo($id = ''){
		$data = json_decode(file_get_contents($this->fileUrl),1);
		foreach ($data as $key =>$value){
			if($value['article_id']==$id){
				return $value;
			}
		}
		return [];
	}
	
	public function down($url,$name){
		$file = fopen('./Data/'.$name,"w+");
		
		$loading = new LoadingService('正在下载');
		
		$source = $url;
		$ch = curl_init();//初始化一个cURL会话
		curl_setopt($ch,CURLOPT_URL,$source);//抓取url
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//是否显示头信息
		curl_setopt($ch,CURLOPT_NOPROGRESS,false);
		curl_setopt($ch,CURLOPT_PROGRESSFUNCTION,function($resource,$total,$bytes) use ($loading){
			if($total>0&&!$loading->getLoadingStatus()){
				$loading->setTotal($total)->start();
			}
			if($bytes>0){
				$increment = $bytes - $this->lastDown;
				$this->lastDown = $bytes;
				if($increment>0&&$loading->getLoadingStatus()){
					$msg = "文件大小:{$this->formatSize($bytes)}/{$this->formatSize($total)} {$this->formatSize($increment)}/s";
					$loading->setMsg($msg)->setTick($increment);
				}
			}
		});
		$data = curl_exec($ch);// 执行一个cURL会话
		
		curl_close($ch);//关闭一个cURL会话并且释放所有资源
		
		fputs($file,$data);//写入文件
		$this->Bar->finish();

		fclose($file);
	}

//格式化size显示
	public function formatSize($b,$times=0){
		if($b>1024){
			$temp=$b/1024;
			return $this->formatSize($temp,$times+1);
		}else{
			switch($times){
				case '0':$unit='B';break;
				case '1':$unit='KB';break;
				case '2':$unit='MB';break;
				case '3':$unit='GB';break;
				case '4':$unit='TB';break;
				case '5':$unit='PB';break;
				case '6':$unit='EB';break;
				case '7':$unit='ZB';break;
				default: $unit='单位未知';
			}
			return sprintf('%.2f',$b).$unit;
		}
	}
	
}